package com.czn.shopdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czn.shopdemo.mapper.*;
import com.czn.shopdemo.model.*;
import com.czn.shopdemo.model.enums.PayStatusEnum;
import com.czn.shopdemo.model.enums.PaymentTypeEnum;
import com.czn.shopdemo.utils.TokenInfoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Zenan Chen
 * @date 2023/4/6 14:49
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements com.czn.shopdemo.service.PaymentService {

    @Autowired
    private PaymentMapper paymentMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private OrderMapper orderMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pay(String orderId, HttpServletRequest request) {
        Payment payment = new Payment();
        // 获取订单明细
        QueryWrapper<OrderItem> orderItemWrapper = new QueryWrapper<>();
        orderItemWrapper.eq("order_id", orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(orderItemWrapper);
        // 统计订单数量、订单总额以及拼接所有下单的商品名称
        Long count = 0l;
        Double price = 0d;
        String goodsName = "";
        for (OrderItem orderItem : orderItems) {
            count += orderItem.getCount();
            price += orderItem.getPrice();
            String goodsId = orderItem.getGoodsId();
            QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
            goodsQueryWrapper.eq("uuid", goodsId);
            Goods goods = goodsMapper.selectOne(goodsQueryWrapper);
            QueryWrapper<Business> businessQueryWrapper = new QueryWrapper<>();
            businessQueryWrapper.eq("uuid", goods.getBusinessId());
            Business business = businessMapper.selectOne(businessQueryWrapper);
            goodsName = goodsName + goods.getName() + "【" + business.getName() + "】  ";
        }
        payment.setCount(count);
        payment.setPrice(price);
        // 拼接订单交易内容
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuilder sb = new StringBuilder();
        sb.append(TokenInfoUtil.getUserName(request)).append("|").append(simpleDateFormat.format(new Date())).append("|").append(goodsName);
        payment.setSubject(sb.toString());
        // 填充用户id
        Long userId = TokenInfoUtil.getUserId(request);
        payment.setUserId(String.valueOf(userId));
        // 填充其他的属性
        payment.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
        payment.setCreateTime(new Date());
        payment.setUpdateTime(new Date());
        payment.setPaymentType(PaymentTypeEnum.AL_PAY.getPayTypeCode());
        payment.setOrderId(orderId);

        paymentMapper.insert(payment);

        // 更新订单支付状态
        updateOrderPayStatus(orderId);

        // 商品库存进行扣减
        goodsReduce(payment);

    }

    private void updateOrderPayStatus(String orderId) {
        Order order = orderMapper.selectOne(Wrappers.<Order>query().lambda().eq(Order::getUuid, orderId));
        order.setOrderStatus(PayStatusEnum.Paid.getPayStatusCode());
        orderMapper.updateById(order);
    }

    /**
     * 商品库存进行扣减
     *
     * @param payment
     */
    private void goodsReduce(Payment payment) {
        String orderId = payment.getOrderId();
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);
        for (OrderItem orderItem : orderItems) {
            String goodsId = orderItem.getGoodsId();
            QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
            goodsQueryWrapper.eq("uuid", goodsId);
            goodsQueryWrapper.eq("on_line", "1");
            Goods goods = goodsMapper.selectOne(goodsQueryWrapper);
            Long count = orderItem.getCount();
            // 库存进行扣减
            goods.setNum(goods.getNum() - count);
            goodsMapper.updateById(goods);
        }
    }
}
